package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("添加分类成功");
    }

    @GetMapping("page")
    public R<Page> page(int page, int pageSize) {
        //1. 分页条件构建器
        Page<Category> p = new Page<>(page, pageSize);

        //2. 查询条件构建器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);

        //3. 执行查询
        categoryService.page(p, lqw);

        //4. 返回数据
        return R.success(p);
    }

    // 删除分类
    @DeleteMapping
    public R<String> delete(Long id) {
        categoryService.removeCategory(id);
        return R.success("删除分类成功");
    }


    // 修改分类
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改分类成功");
    }


    @GetMapping("list")
    public R<List<Category>> list(Category category) {
        //1. 创建条件构建器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //1.1 设置查询条件
        lqw.eq(category.getType() != null, Category::getType, category.getType());
        //1.2 设置排序规则
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //2. 执行查询
        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }
}
